package com.zpself.module.算法练习.算法;

import java.util.Arrays;

/**
 * @author By ZengPeng
 * @Description 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，
 * 写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。斐波拉且
 * @date in  2021/2/11 20:16
 * @Modified By
 */
public class 力扣_704_二分查找 {
    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3,6,7,9,10,11,15,21,23,25,26};
        System.out.println(search(arr, 2));
        System.out.println(search(arr, 3));
        System.out.println(search(arr, 6));
        System.out.println(search(arr, 12));
    }
    public static int search(int[] nums, int target) {
        int left = 0 ,right = nums.length-1,middle;
        while (left<=right){
            middle = (left+right)>>>1;
            if(target == nums[middle]){
                return middle;
            }else  if(target > nums[middle]){
                left = middle+1;
            }else {
                right = middle-1;
            }

        }
       return -1;
    }

    public int search2(int[] nums, int target) {
        int i = Arrays.binarySearch(nums, target);
        if (i>=0){
            return i;
        }else {
            return -1;
        }
    }
}
